package com.example.college;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;




public class MainActivity extends Activity implements OnClickListener {
	// flag for Internet connection status
		Boolean isInternetPresent = false;
		
		// Connection detector class
		ConnectionDetector cd;


	Intent intent;
	// Progress Dialog
	  private ProgressDialog pDialog;

        JSONParser jsonParser = new JSONParser();
        
        EditText senduser;
        EditText sendpass;
        
     // url to send username and password
     	private static String url_send_data = "http://192.168.140.1:8080/WebApplication2/webresources/login/";
	
     // JSON Node names
     	private static final String TAG_SUCCESS = "success";
     	
     	
     	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		Button btnStatus = (Button) findViewById(R.id.checkconnection);
		
		// creating connection detector class instance
		cd = new ConnectionDetector(getApplicationContext());
		
		
		/**
		 * Check Internet status button click event
		 * */
		btnStatus.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View view) {
				// get Internet status
				isInternetPresent = cd.isConnectingToInternet();
				
				// check for Internet status
				if (isInternetPresent) {
					// Internet Connection is Present
					// make HTTP requests
					showAlertDialog(MainActivity.this, "Internet Connection",
							"You have internet connection", true);
				}else {
					// Internet connection is not present
					// Ask user to connect to Internet
					showAlertDialog(MainActivity.this, "No Internet Connection",
							"You don't have internet connection.", false);
				}

				
			}
		});
		
		
		
		
		

		//Edit Text
		senduser=(EditText) findViewById(R.id.login_name);
		sendpass=(EditText) findViewById(R.id.login_pass);
		
		Button button=(Button) findViewById(R.id.login);
		button.setOnClickListener(this);
		
		intent=new Intent(getApplicationContext(),Student.class);
		

				




		
		
		
		
		
	}
	
	
	
	
	public void onRadioButtonClicked(View view) {
	    // Is the button now checked?
	    boolean checked = ((RadioButton) view).isChecked();
	    
	    

	    switch(view.getId()) {
	        case R.id.radio_student:
	        	if (checked)
	            	intent=new Intent(getApplicationContext(),Student.class);
	    	          break;
	        
	        
	        case R.id.radioinstructor:
	            if (checked)
	            	intent=new Intent(getApplicationContext(),Doctor.class);
	   	             break;
	    
	    }
	
		
	
	
	}
	
	/**
	 * Background Async Task to Add Grades
	 * */
	class SendInfo extends AsyncTask<String, String, String>{
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog=new ProgressDialog(MainActivity.this);
			pDialog.setMessage("Login..Please Wait");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(true);
			pDialog.show();
		}

		/**
		 * Login
		 * */
		@Override
		protected String doInBackground(String... args) {
			String username=senduser.getText().toString();
			String pass=sendpass.getText().toString();
			
			// Building Parameters
			 List<NameValuePair> params = new ArrayList<NameValuePair>();
			 //params.add(new BasicNameValuePair("Username", username));
			 //params.add(new BasicNameValuePair("Password", pass));
			 url_send_data = url_send_data +username+"/"+pass;
			 
			// getting JSON Object
				// Note that login url accepts POST method
			 JSONObject json = jsonParser.makeHttpRequest(url_send_data,
						"GET", params);
			// check log cat for response
				Log.d("login response", json.toString());
				
				// check for success tag
				
					//int success = ;
				if(json!= null)
					try {
						intent.putExtra("id", json.getString("UMail"));
						intent.putExtra("type", json.getString("UType"));
						
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
//					if (json != null) {
//						// successfully login
//						Toast toast=Toast.makeText(getApplicationContext(), "login success", Toast.LENGTH_LONG);
//						toast.show();
//						
//						// closing this screen
//						finish();
//					} else {
//						// failed to login
//						Toast toast=Toast.makeText(getApplicationContext(), "login Failed", Toast.LENGTH_LONG);
//						toast.show();
//					}
				

			 
			 
			return null;
		}
		
		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		@Override
		protected void onPostExecute(String file_url) {
			// dismiss the dialog once done
			pDialog.dismiss();
			startActivity(intent);

		}
		
		
	}
	
	
	@Override
	public void onClick(View view) {
		// sending name and password in background thread
		new SendInfo().execute();
//		startActivity(intent);
		
	}
	
	/**
	 * Function to display simple Alert Dialog
	 * @param context - application context
	 * @param title - alert dialog title
	 * @param message - alert message
	 * @param status - success/failure (used to set icon)
	 * */	
	public void showAlertDialog(Context context, String title, String message, Boolean status) {
		AlertDialog alertDialog = new AlertDialog.Builder(context).create();

		// Setting Dialog Title
		alertDialog.setTitle(title);

		// Setting Dialog Message
		alertDialog.setMessage(message);
		
		// Setting alert dialog icon
		alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);

		// Setting OK Button
		alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
			}
		});

		// Showing Alert Message
		alertDialog.show();
	}	
		
	


		
	






	

}
